<template>
    <div style=" position: relative;"><el-card>
            <template #header>
                <!-- 搜索 -->
                <div>
                    <el-input style="width: 200px;" v-model="find_data.typeName" placeholder="请输入金额类型名称" clearable
                        prefix-icon="Search" />
                    <el-select style="margin-left: 20px;width:150px" v-model="find_data.profitDirection"
                        placeholder="请选择利润方向" clearable>
                        <el-option v-for="item in profit" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>

                    <el-button style="margin-left: 20px;height:30px" @click="search_btn" type="primary"
                        icon="Search">搜索</el-button>
                </div>
                <!-- 功能按钮 -->
                <div style="margin-top:10px;display: flex;">
                    <el-button @click="add_btn(0, '')" type="primary" icon="SuccessFilled">新增一级金额类型</el-button>
                </div>
            </template>
            <div>
                <el-table border @selection-change="selection_change_btn" height="67vh" ref="multipleTableRef"
                    :data="list_data" style="width: 100%" row-key="id"
                    :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
                    <!-- <el-table-column type="selection" width="35" /> -->
                    <el-table-column label="编号" width="55" fixed type="index" />
                    <template v-for="item in table_data_list_new" :key="item.field">
                        <el-table-column v-if="item.off" :width="item.width" :prop="item.field" :label="item.label">
                            <template v-if="item.field == 'typeName'" #="{ row, column, $index }">
                                <span :class="{
                                    paddingLeft: row.typeLevel === 2,
                                    paddingLeft_3: row.typeLevel === 3,
                                }">
                                    {{ row.typeName }}
                                </span>
                            </template>
                            <template v-if="item.field == 'profitDirection'" #="{ row, column, $index }">
                                <span
                                    :style="row.profitDirection == 'INCOME' ? 'color: red' : row.profitDirection
                                        == 'OUTPAY' ? 'color:#008000' : row.profitDirection == 'TRANS' ? 'color:#FD7350' : ''">{{
        row.profitDirection == 'INCOME' ? '收入类' : row.profitDirection
            == 'OUTPAY' ? '支出类' :
        row.profitDirection == 'TRANS' ? '互转类' : '暂无该类型' }}</span>
                            </template>
                            <template v-if="item.field == 'operate'" #="{ row, column, $index }">
                                <el-button style="color: #6DA6FE;" v-if="row.typeLevel < 3" link size="small"
                                    @click="add_btn(1, row)">
                                    添加
                                </el-button>

                                <el-button style="color: #6DA6FE;" v-if="row.isDefault === 0" link size="small"
                                    @click="add_btn(2, row)">
                                    修改
                                </el-button>

                                <el-button style="color: #6DA6FE;" v-if="row.isDefault === 0" link size="small"
                                    @click="del_btn(row)">
                                    删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </template>


                </el-table>
            </div>

            <div style="margin-top:20px">
                <el-pagination @current-change="current_change_btn" @size-change="size_change_btn"
                    v-model:current-page="find_data.page.pageNum" v-model:page-size="find_data.page.pageSize"
                    :page-sizes="[20, 50, 100, 200]" :background="true" layout="prev, pager, next, jumper,->,sizes,total,"
                    :total="total" />
            </div>
        </el-card>
    </div>

    <!-- 弹窗 -->
    <div>
        <!-- 表格筛选 -->
        <div style="position: absolute;top:100px;z-index: 9999;" :style="icon_off ? 'right:0px;' : 'right:110px;'">
            <el-icon @click="icon_btn" :size="20">
                <Setting />
            </el-icon>
            <div v-show="icon_off"
                style=" position: relative;top:-100px;right:140px;width: 130px;height:430px;background:#fff;overflow: hidden;">
                <div class="cols-set" style="background:#fff;width:90%;height:97%;margin:auto;margin-top:10px;">
                    <div>
                        <el-button-group style="display: flex; ">
                            <el-tooltip effect="dark" placement="bottom">
                                <template #content>注意：拖动下面的项，可以改变表格列的顺序，<br />记得点击保存才会永久生效哦！ </template>
                                <el-button style="width:10px" type="primary" icon="WarningFilled"></el-button>
                            </el-tooltip>
                            <el-button title="重置" type="primary" icon="Refresh" @click="resetTableSet"></el-button>
                            <el-button title="保存" type="primary" icon="Check" @click="saveTableSet"></el-button>
                        </el-button-group>
                        <div ref="sortableContainer" class="col-items" style="height:400px; overflow-y: auto; ">
                            <el-checkbox class="drag_it" @change="checkbox_btn" v-for="item in sortedItems"
                                :key="item.field" v-model="item.off" :label="item.label" border>
                            </el-checkbox>
                        </div>

                    </div>
                </div>
            </div>
        </div>
        <!-- 添加修改 -->
        <el-dialog style="margin-top:5vh" v-model="add_off" :title="title" width="40%" :close-on-click-modal='false'>
            <el-form :model="add_data" label-width="130px" label-suffix="：">
                <el-form-item v-if="add_data.typeName1" label="父级类型" prop="typeName">
                    【{{ add_data.typeName1 }}】类型
                </el-form-item>
                <el-form-item label="金额类型">
                    <el-input style="width: 220px;" v-model="add_data.typeName" placeholder="请输入金额类型名称" />
                </el-form-item>

                <el-form-item v-if="add_data.type == 0 || add_data.type == 2" label="利润方向">
                    <el-select :disabled="(add_data.type == 2 && add_data.upTypeId) ? true : false"
                        v-model="add_data.profitDirection" placeholder="请选择利润方向" clearable>
                        <el-option v-for="item in profit" :key="item.value" :label="item.label" :value="item.value" />
                    </el-select>
                </el-form-item>

                <el-form-item label="报账部门选择">
                    <el-cascader v-model="curval2" :options="findAllDeptList_list" :collapse-tags="true" :clearable="true"
                        :props="{ multiple: true, checkStrictly: true, emitPath: true, value: 'id', label: 'deptName' }"
                        placeholder="请选择部门" :show-all-levels="false" @change="handleChange_find">
                        <template #="{ node, data }">
                            <span>{{ data.deptName }}</span>
                            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                        </template>
                    </el-cascader>
                </el-form-item>


                <el-form-item label="报账角色选择">
                    <el-cascader v-model="curval" :options="getRoleList_list" :collapse-tags="true" :clearable="true"
                        :props="{ multiple: true, checkStrictly: false, emitPath: true, value: 'id', label: 'roleName' }"
                        placeholder="报账角色选择" :show-all-levels="false" @change="handleChange">
                        <template #="{ node, data }">
                            <span>{{ data.roleName }}</span>
                            <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                        </template>
                    </el-cascader>
                </el-form-item>

            </el-form>


            <el-button @click="ok_btn" style="margin-left:30vw" type="primary">确认提交</el-button>
        </el-dialog>
    </div>
</template>

<script setup>
import Sortable from 'sortablejs';
import { ref, reactive, onMounted, computed } from 'vue'
import {
    line2treeData, findP2CArr, setFmArr

} from '@/utils/common.js'

import {
    adupPrivateSet, getPrivateSetList, getMoneyTypeList, addMtype, delMtype, modifyMtype, getRoleList, findAllDeptList

} from '@/api/system_management.js'
import { ElMessage, ElLoading, ElMessageBox } from 'element-plus'
import CircularJSON from 'circular-json'
onMounted(async () => {
  

    getPrivateSetList({
        find: '金额类型',
        page: {
            pageNum: 1,
            pageSize: 20,
        },
    }).then(res => {
        if (res.data.list[0]) {
            table_data_list_new.value = JSON.parse(res.data.list[res.data.list.length - 1].dat)
        } else {
            console.log('no')
            table_data_list_new.value = table_data_list
        }
    })



    Sortable.create(sortableContainer.value, {
        draggable: '.drag_it',
        ghostClass: 'sortable-ghost',
        onEnd: evt => {
            const targetRow = table_data_list_new.value.splice(evt.oldIndex, 1)[0];
            table_data_list_new.value.splice(evt.newIndex, 0, targetRow);

        }
    })


    findAllDeptList({}).then(res => {
        findAllDeptList_list.value = res.data
        findAllDeptList_list.value = line2treeData(findAllDeptList_list.value, 'pid')
        findAllDeptList_list.value = findAllDeptList_list.value[0].children
    })


    await list_api()

})
const findAllDeptList_list = ref([])
//#region 表格数据处理
const table_data_list = reactive([
    { label: '金额类型', field: 'typeName', width: '', off: true },
    { label: '利润方向', field: 'profitDirection', width: '', off: true },
    { label: '角色', field: 'roleNames', width: '', off: true },
    { label: '操作', field: 'operate', width: '', off: true },
])
const handleChange_find = (valarr) => {
    console.log(valarr)
    let arr = []
    if (valarr) {

        for (let i = 0; i < valarr.length; i++) {
            arr.push(valarr[i])
        }

        add_data.deptIds = arr
    }
    getRoleList({ deptIds: arr.join(',') }).then(res => {
        getRoleList_list.value = res.data
        getRoleList_list.value = line2treeData(getRoleList_list.value, 'pid')
    })

}
const table_data_list_new = ref([])
const icon_off = ref(false)
// 创建排序容器的引用
const sortableContainer = ref('')

const icon_btn = () => {
    icon_off.value = !icon_off.value
    console.log(sortableContainer.value)

}
const resetTableSet = () => {
    console.log(table_data_list)
    table_data_list_new.value = JSON.parse(JSON.stringify(table_data_list))
    console.log(table_data_list)
    console.log(table_data_list_new.value)
}
const saveTableSet = () => {
    adupPrivateSet({
        dat: JSON.stringify(table_data_list_new.value),
        tbName: '金额类型',
        tbNum: "amount_type",
    }).then(res => {
        if (res.code == 1) {
            return ElMessage({
                message: res.msg,
                type: 'success',
            })
        } else {
            return ElMessage({
                message: res.msg,
                type: 'warning',
            })
        }
    })
    icon_off.value = false
}

const checkbox_btn = (e, c) => {
    for (let i = 0; i < table_data_list_new.value.length; i++) {
        if (table_data_list_new.value[i].label == c.target._value) {
            table_data_list_new.value[i].off == e

        }

    }

}

const sortedItems = computed(() => {
    return [...table_data_list_new.value].sort((a, b) => a.id - b.id);
})
//#endregion

//#region 利润方法
const profit = reactive([
    { value: "INCOME", label: "收入类", color: 'c-red' },
    { value: "OUTPAY", label: "支出类", color: 'c-green' },
    { value: "TRANS", label: "互转类", color: 'c-yellow' },
])
//#endregion
//#region 分页列表
const list_data = ref([])
const find_data = reactive({
    page: {
        pageNum: 1,
        pageSize: 20,
    },
    typeName: '',
    profitDirection: '',
})
const total = ref(0)

// 分页器一夜显示多少数据页面
const size_change_btn = () => {
    find_data.page.pageNum = 1
    list_api()
}

// 分页器跳转页面
const current_change_btn = () => {
    list_api()
}

const list_api = () => {

    getMoneyTypeList(find_data).then(res => {
        list_data.value = res.data.list
        total.value = res.data.total

    })
}
//#endregion

//#region 添加
const add_off = ref(false)
const title = ref('添加金额类型')
const curval = ref([])
const curval2 = ref([])
const getRoleList_list = ref([])
const handleChange = (valarr) => {
    console.log('点击了', valarr);

    valarr.forEach(it => { add_data.roleIds.push(it[it.length - 1]); });


    setFmArr(add_data.roleIds, valarr)
}
const add_data = reactive({
    btlIds: '',
    profitDirection: '',
    rtIds: "",
    roleIds: [],
    checkOutTime: "",
    sfIds: "",
    typeName: "",
    typeName1: "",
    upTypeId: "",
    type: '1',
    id: '',
    deptIds: [],
})
const findStationCombo_data_list = ref([])
const add_btn = (e, row) => {
    title.value = '添加金额类型'
    add_data.btlIds = ''
    add_data.profitDirection = ''
    add_data.rtIds = ''
    add_data.checkOutTime = ''
    add_data.sfIds = ''
    add_data.typeName = ''
    add_data.typeName1 = ''
    add_data.type = ''
    add_data.id = ''
    add_data.deptIds = []
    add_data.roleIds = [] // 问题
    curval.value = ''
    curval2.value = ''
    if (e == 0) {
        add_data.upTypeId = 0
        add_data.type = e
    } else if (e == 1) {
        add_data.type = e
        add_data.upTypeId = row.id
        add_data.typeName1 = row.typeName
        add_data.profitDirection = row.profitDirection
        console.log(row, '1')
    } else if (e == 2) {
        getRoleList({}).then(res => {
            getRoleList_list.value = res.data
            getRoleList_list.value = line2treeData(getRoleList_list.value, 'pid')
        })
        title.value = '修改金额类型'
        add_data.type = e
        add_data.roleIds = row.roleIds.split(",")
        add_data.deptIds = row.deptIds.split(",")
        
        curval.value = add_data.roleIds.map(str => parseInt(str))
        curval2.value = add_data.deptIds.map(str => parseInt(str))

        add_data.upTypeId = row.upTypeId || 0
        add_data.id = row.id
        add_data.typeName = row.typeName
        add_data.profitDirection = row.profitDirection
    }

    add_off.value = true

}


//#endregion

//#region 表格选择
const table_list = ref([])
const selection_change_btn = (e) => {
    table_list.value = e
    console.log(e)
}
//#endregion
//#region 修改
const up_btn = () => {
    if (table_list.value.length != 1) {
        return ElMessage({
            message: '请选择一条数据！',
            type: 'warning',
        })
    }

    // add_data.roleIds = row.roleIds.split(",")
    title.value = '修改金额类型'



    add_off.value = true
}
//#endregion

// 提交
const ok_btn = () => {
    if (!add_data.typeName) {
        return ElMessage({
            message: '请输入类型名称',
            type: 'warning',
        })
    } else if (!add_data.profitDirection) {
        return ElMessage({
            message: '请选择利润方向',
            type: 'warning',
        })
    } else if (!add_data.roleIds[0]) {
        return ElMessage({
            message: '请选择角色',
            type: 'warning',
        })
    } else if (!add_data.deptIds[0]) {
        return ElMessage({
            message: '请选择部门',
            type: 'warning',
        })
    }


    if (title.value == '添加金额类型') {
        if (add_data.roleIds[0]) {
            console.log(add_data.roleIds[0])
            add_data.roleIds = add_data.roleIds.join(',')
        }
        if (add_data.deptIds[0]) {
            console.log(add_data.deptIds[0])
            add_data.deptIds = add_data.deptIds.join(',')
        }

        addMtype(add_data).then(res => {
            if (res.code == 1) {
                list_api()
                add_off.value = false
                return ElMessage({
                    message: res.msg,
                    type: 'success',
                })
            } else {
                add_off.value = false
                return ElMessage({
                    message: res.msg,
                    type: 'warning',
                })
            }
        })
    } else {
        if (add_data.roleIds[0]) {
            add_data.roleIds = add_data.roleIds.join(',')
        }
        if (add_data.deptIds[0]) {
            add_data.deptIds = add_data.deptIds.join(',')
        }
        modifyMtype(add_data).then(res => {
            if (res.code == 1) {
                list_api()
                add_off.value = false
                return ElMessage({
                    message: res.msg,
                    type: 'success',
                })
            } else {
                return ElMessage({
                    message: res.msg,
                    type: 'warning',
                })
            }
        })
    }
}


//#region 删除
const del_btn = (e) => {


    ElMessageBox.confirm(
        `是否确认删除【${e.typeName}】`,
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
            distinguishCancelAndClose: 'true',
        }
    )
        .then(() => {
            delMtype({
                id: e.id
            }).then(res => {
                if (res.code == 1) {
                    list_api()
                    return ElMessage({
                        message: res.msg,
                        type: 'success',
                    })
                } else {
                    return ElMessage({
                        message: res.msg,
                        type: 'warning',
                    })
                }
            })
        })
        .catch((e) => {
            if (e == 'cancel') {
                ElMessage({
                    type: 'warning',
                    message: '取消删除成功',
                })
            }

        })

}
//#endregion

//#region 搜索
const search_btn = () => {
  
    list_api()
}


</script>

<style scoped lang='scss'>
.paddingLeft {
    padding-left: 24px;
}

.paddingLeft_3 {
    padding-left: 48px;
}
</style>

<style>
.col-items::-webkit-scrollbar {
    width: 5px !important;
}

.col-items>label {
    margin-left: 0px !important;
    margin-top: 5px;
    width: 100%;
}


.el-table .el-table__cell {
    padding: 0px !important;
}
</style>
